package com.bw.mallshop.mvvm.model;

import android.text.TextUtils;

import com.bw.common.entity.BaseEntity;
import com.bw.common.mvvm.model.BaseModel;
import com.bw.common.network.HttpType;
import com.bw.common.network.RetrofitFactory;
import com.bw.mallshop.entity.UpdateImgEntity;
import com.bw.mallshop.entity.UserEntity;
import com.bw.mallshop.repository.ApiService;

import java.io.File;
import java.util.Map;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class EdtUserModel extends BaseModel {

    //编辑用户信息
    public Observable<BaseEntity>requestEdtUser(Map<String,Object>parames){
        Observable<UserEntity>observable = RetrofitFactory.factory(HttpType.TOKENSIGN)
                .createRetrofit().create(ApiService.class)
                .requestEdtUser(createBody(parames));
        return changeObservable(observable);
    }
    //上传头像
    public Observable<BaseEntity>requestUpdateHead(String path){
        if (TextUtils.isEmpty(path)){
            UpdateImgEntity entity = new UpdateImgEntity();
            entity.statuesCode = "100";
            entity.message = "路径为空";
            return Observable.just(entity);
        }
        File file = new File(path);
        if (!file.exists()){
            UpdateImgEntity entity = new UpdateImgEntity();
            entity.statuesCode = "100";
            entity.message = "未找到文件";
            return Observable.just(entity);
        }
        String name = path.substring(path.lastIndexOf("/")+1,path.lastIndexOf("."));
        //生成Retrofit上传图片封装
        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"),file);
        MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
        multipartBuilder.addFormDataPart("file",name,body);
//        multipartBuilder.addFormDataPart("","");//当上传得数据需要额外添加参数时，需要使用此种方式
        Observable<UpdateImgEntity>updateImgEntityObservable = RetrofitFactory.factory(HttpType.NOMAL)
                .createRetrofit().create(ApiService.class)
                .requestUploadImg(multipartBuilder.build().parts());
        return changeObservable(updateImgEntityObservable);
    }

}
